import { MoodModel, type Mood } from "../db/model";

export class MoodService {
  // 获取用户的所有心情记录
  async getMoods(userId: string) {
    const moods = await MoodModel.find({ userId }).sort({ createdAt: -1 });
    return moods;
  }

  // 创建心情记录
  async createMood(data: {
    userId: string;
    mood: { level: 1 | 2 | 3 | 4 | 5 };
    remark: string;
  }) {
    return await MoodModel.create({
      ...data,
      createdAt: new Date(),
    });
  }

  // 获取单个心情记录
  async getMood(userId: string, moodId: string) {
    const mood = await MoodModel.findOne({ _id: moodId, userId });
    if (!mood) {
      throw new Error("心情记录不存在");
    }
    return mood;
  }

  // 更新心情记录
  async updateMood(userId: string, moodId: string, data: {
    mood?: { level: 1 | 2 | 3 | 4 | 5 };
    remark?: string;
  }) {
    const mood = await MoodModel.findOneAndUpdate(
      { _id: moodId, userId },
      { $set: data },
      { new: true }
    );

    if (!mood) {
      throw new Error("心情记录不存在");
    }

    return mood;
  }

  // 删除心情记录
  async deleteMood(userId: string, moodId: string) {
    const result = await MoodModel.findOneAndDelete({ _id: moodId, userId });
    if (!result) {
      throw new Error("心情记录不存在");
    }
    return true;
  }

  // 获取心情统计数据
  async getMoodStats(userId: string) {
    const [moods, total] = await Promise.all([
      MoodModel.find({ userId }).sort({ createdAt: -1 }).limit(30),
      MoodModel.countDocuments({ userId })
    ]);

    // 统计各等级心情数量
    const byLevel = moods.reduce((acc, mood) => {
      const level = mood.mood.level;
      acc[level] = (acc[level] || 0) + 1;
      return acc;
    }, {} as Record<number, number>);

    // 获取最近趋势
    const recentTrend = moods.map(mood => ({
      date: mood.createdAt.toISOString().split('T')[0],
      level: mood.mood.level
    }));

    return {
      total,
      byLevel,
      recentTrend
    };
  }
}
